package org.flexlancer.databases
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	public class ProductCategory extends EventDispatcher
	{
		public static var LastInsertedID:Number = -1;
		private static const TABLE:String = "productcategory";
		
		public function ProductCategory(target:IEventDispatcher=null)
		{
			super(target);
		}
		
		public static function Add(parmCategoryName:String,parmParentID:String):void{
			try{
				var insertObj:Object = new Object();
				insertObj.catname = " '" + parmCategoryName + "' ";
				insertObj.products = "0";
				insertObj.parentid = parmParentID;
				DatabaseManager.Manager.Insert(TABLE,insertObj);
				LastInsertedID = DatabaseManager.Manager.LastInsertRowID;
			}catch(err:Error){
				throw err;
			}
		}
		
		public static function Delete(parmCategoryID:String):void{
			try{
				DatabaseManager.Manager.Delete(TABLE,"catid = "+parmCategoryID);
			}catch(err:Error){
				throw err;
			}
		} 
		
		public static function List(condition:String = ""):Array{
			try{
				return DatabaseManager.Manager.Select(TABLE,null,condition,"catname");
			}catch(err:Error){
				throw err;
			}
			return null;
		}
		
		public static function Tree():XML{
			try{
				return new XML("<node>"+BuildTree("0").toXMLString()+"</node>");
			}catch(err:Error){
				throw err;
			}
			return null;
		}
		
		private static function BuildTree(parmID:String):XMLList{
			try{
				var arrList:Array = List("parentid="+parmID);
				var xmlReturn:XML = new XML(<node />);
				
				for each ( var singleObj:Object in arrList ){
					var insertNode:XML = new XML("<node />");
					insertNode.@id = singleObj.catid;
					insertNode.@name = singleObj.catname;
					insertNode.@parentid = singleObj.paretnid;
					
					insertNode.appendChild(BuildTree(singleObj.catid));
					xmlReturn.appendChild(insertNode);
				}
				return xmlReturn.children();
			}catch(err:Error){
				throw err;
			}
			return null;
		}
	}
}